package routers

import (
	"github.com/gin-gonic/gin"
	"net/http"
)

type User struct {
	Name string `form:"name" json:"name"`
	Age  int    `form:"age" json:"age"`
}

func ParamRouter(r *gin.Engine) {
	router := r.Group("/")
	router.GET("/news", func(c *gin.Context) {
		c.HTML(http.StatusOK, "news.html", gin.H{
			"name": "chj",
			"age":  20,
		})
	})

	router.GET("/query", func(c *gin.Context) {
		name := c.Query("name")
		age := c.DefaultQuery("age", "20")
		c.JSON(http.StatusOK, gin.H{
			"name": name,
			"age":  age,
		})
	})

	router.POST("/form1", func(c *gin.Context) {
		name := c.PostForm("name")
		age := c.DefaultPostForm("age", "20")
		c.JSON(http.StatusOK, gin.H{
			"name": name,
			"age":  age,
		})
	})

	router.POST("/form2", func(c *gin.Context) {
		user := &User{}
		err := c.ShouldBind(user)
		if err != nil {
			c.JSON(http.StatusBadRequest, gin.H{
				"err": err,
			})
		}
		c.JSON(http.StatusOK, user)
	})

	router.GET("/param/:id", func(c *gin.Context) {
		id := c.Param("id")
		c.JSON(http.StatusOK, gin.H{
			"id": id,
		})
	})
}
